package com.ykl.demo.comp.conv;

import com.ykl.demo.entity.SpcRoom;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.util.Set;

/**
 * .
 * <p></p>
 *
 * @author 王东石 2021/11/28 10:30.
 */
public abstract class AbstractConverter<S,T> implements AutoRegisterConverter<S,T> {


    @Autowired
    private Validator validator;


    @Override
    public T convert(S source) {
        T target = conv(source);


        Set<ConstraintViolation<T>> errs = validator.validate(target);
        if(!CollectionUtils.isEmpty(errs)){
            StringBuilder msg = new StringBuilder();
            errs.forEach(err->{
                msg.append(msg.length()>0?",":"").append(err.getMessage());
            });
            throw new ValidateFailException(msg.toString());
        }

        return target;
    }

    protected abstract T conv(S sourc);
}
